package net.biancheng.framework.web.controller;

import net.biancheng.common.core.CommonResult;
import net.biancheng.common.utils.SecurityUtils;
import net.biancheng.framework.web.service.SysLoginService;
import net.biancheng.framework.web.service.SysPermissionService;
import net.biancheng.model.LoginBody;
import net.biancheng.model.RegisterBody;
import net.biancheng.bean.SysMenu;
import net.biancheng.bean.SysUser;
import net.biancheng.service.ISysMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;


/**
 * @author: lb
 * @date: 2021/8/17 9:15
 * @desc: 登录相关请求controller
 */
@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService sysLoginService;
    
    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysMenuService sysMenuService;


    /**
     * 登录
     * @param loginBody
     * @return
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginBody loginBody){
        CommonResult result = CommonResult.success();
        String token = sysLoginService.login(loginBody.getUserName(), loginBody.getPassword());
        result.put("token", token);
        return result;
    }


    /**
     * 注册
     * @param registerBody
     * @return
     */
    @PostMapping("/register")
    public CommonResult register(@RequestBody RegisterBody registerBody) {
        String message = sysLoginService.register(registerBody);
        if (StringUtils.isNotEmpty(message)){
            return CommonResult.error(message);
        }
        return CommonResult.success();
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    public CommonResult getUserInfo(){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        //菜单权限集合
        Set<String> menus = permissionService.getMenuPermission(user);
        CommonResult result = CommonResult.success();
        result.put("user", user);
        result.put("roles", roles);
        result.put("permissions", menus);
        return result;
    }

    /**
     * 获取路由信息
     * @return
     */
    @GetMapping("/getRouters")
    public CommonResult getRouters(){
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = sysMenuService.selectSysMenuTreeByUserId(userId);
        return CommonResult.success(sysMenuService.buildRouterMenus(menus));
    }


}
